package com.shakespace.artofandroid.chapter03.basic

import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.Scroller

class DemoView @JvmOverloads constructor(context: Context?, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
    View(context, attrs, defStyleAttr) {


    val scroller = Scroller(context)

    /**
     * // 2020-01-14 NOTE: typical use for  scroller , it must be work with View.computeScroll()
     */
    fun smoothScrollTo(destX: Int, dextY: Int) {
        val delta = destX - scrollX
        // smooth move to destX in 1000ms
        // 2020-01-15 NOTE: startScroll only save some params , include finalX, finalY
        scroller.startScroll(scrollX, 0, delta, 0, 1000)
        // will call draw(xxx,xxx,xxx)? --> computeScroll() --> postInvalidate() -->...
        invalidate()
    }

    override fun computeScroll() {
        /**
         * if (mCurrX == mFinalX && mCurrY == mFinalY) {
         *      mFinished = true;
         *  }
         *
         * so if false here , mean still in moving . will calc new currX and currY , and scrollTo
         */
        if (scroller.computeScrollOffset()) {
            scrollTo(scroller.currX, scroller.currY)
            postInvalidate()
        }
    }

    /**
     * there are three ways to scroll a view （滑动一个view的三种方式）
     * 1. scrollTo / scrollBy
     *      scrollTo : absolutely move with params
     *      scrollBy : relatively
     *
     *      scrollX :  View 左边缘 和 内容 左边缘的距离  View.left - inner .left?
     *      scrollY ： View 上边缘和内容 上边缘的距离
     *      scroll 改变的是View内容的位置，而不是View的位置
     *
     *      从左往右滑动 --》 scrollX < 0
     *      从上往下滑动 --》 scrollY < 0
     *
     * 2. Animation (transition)
     *      much better
     * 3. change layoutparams
     *      a little complex
     */

    // animation
    fun moveByAnimation() {
        // 2020-01-15 NOTE: will really change the position of targetView , if use xml , need use fillAfter = true .
        ObjectAnimator.ofFloat(this, "translationX", 0F, 100F)
            .setDuration(100)
            .start()


        // use animator to do a smooth scroll
        val startX = 0
        val deltaX = 100
        val animator = ValueAnimator.ofInt(0, 100).setDuration(1000)
        animator.addUpdateListener {
            // 2020-01-15 NOTE: 当前动画完成的比例 ？
            val fraction = it.animatedFraction
            this.scrollTo(startX + (deltaX * fraction).toInt(), 0)
        }
        animator.start()
    }

    // change layoutParam
    fun moveByChangeLayoutParam() {
        layoutParams.width += 100
        layoutParams.height += 100

        this.layoutParams = layoutParams
//       or  requestLayout()
    }

    fun test(){
//        this.setOnClickListener()
    }
}